package com.right.health.app.ui.me;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.magic.basic.activity.BaseActivity;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.bean.FamilyResponse;
import com.right.health.app.bean.PositionInfo;
import com.right.health.app.bean.ReviewReminderInfo;
import com.right.health.app.common.DataCommon;
import com.right.health.app.constants.BroadCastKey;
import com.right.health.app.dialog.BottomPickerDialog;
import com.right.health.app.dialog.DateBottomPickerDialog;
import com.right.health.app.net.RemindApi;
import com.right.health.app.ui.me.adapter.ReviewReminderAddAdapter;

import java.util.ArrayList;
import java.util.List;

import static com.right.health.app.constants.BroadCastCode.RREFRESH_DRUGREINDE;

/*
 * Created by hopeliao on 2019-09-29
 * 用药提醒新增
 *
 */
public class ReviewReminderAddActivity extends BaseActivity implements View.OnClickListener, OnHttpListener {

    private static final int HANDLE_TYPE_END_TIME = 1;
    private static final int HANDLE_TYPE_START_TIME = 2;

    private static final int REQUEST_CODE_FAMILY = 1;

    private ReviewReminderAddAdapter mAdapter;

    private List<ReviewReminderInfo> mDataSource = new ArrayList<>();

    private DateBottomPickerDialog mDateDialog;

    private PositionInfo mPositionInfo = new PositionInfo();

    private BottomPickerDialog<BottomPickerDialog.BottomPickerInfo> mPickerDialog;
    private BottomPickerDialog<BottomPickerDialog.BottomPickerInfo> mTipsTimeDialog;

    private List<BottomPickerDialog.BottomPickerInfo> mCycleDataSource = new ArrayList<>();
    private List<BottomPickerDialog.BottomPickerInfo> mTipsTimeDataSource = new ArrayList<>();

    private TextView mNameTv;

    private RemindApi mRemindApi;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.review_reminder_add);
    }

    @Override
    public void findView() {
        mNameTv = (TextView) findViewById(R.id.tv_name);
        findViewById(R.id.tv_switch_member).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);

        ListView listView = (ListView) findViewById(R.id.listview);
        mAdapter = new ReviewReminderAddAdapter(this);
        mAdapter.setOnClickListener(this);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startIntent(ReviewReminderDetailActivity.class);
            }
        });

        View footView = LayoutInflater.from(this).inflate(R.layout.review_reminder_add_footer, null);
        footView.findViewById(R.id.ib_add).setOnClickListener(this);
        listView.addFooterView(footView);
    }

    @Override
    public void initialize() {
        String[] cycleArrays = getResources().getStringArray(R.array.review_reminder_cycle_arrays);
        for (String str : cycleArrays) {
            mCycleDataSource.add(new BottomPickerDialog.BottomPickerInfo(str));
        }

        String[] tipsTimeArrays = getResources().getStringArray(R.array.review_reminder_tips_arrays);
        for (String str : tipsTimeArrays) {
            mTipsTimeDataSource.add(new BottomPickerDialog.BottomPickerInfo(str));
        }

        mNameTv.setText(App.getInstance().getCurrentMember().name);

        mRemindApi = new RemindApi();
        mRemindApi.setListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_FAMILY) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    FamilyResponse.FamilyInfo mFamilyInfo = bundle.getParcelable(BroadCastKey.DATA);
                    if (mFamilyInfo != null) {
                        mNameTv.setText(mFamilyInfo.membername);
                    }
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_choose_time: //选择时间
                mPositionInfo.position = (int) v.getTag();
                mPositionInfo.type = HANDLE_TYPE_START_TIME;

                getDateDialog(mPositionInfo).show();
                break;
            case R.id.tv_end_time: //结束时间
                mPositionInfo.position = (int) v.getTag();
                mPositionInfo.type = HANDLE_TYPE_END_TIME;

                getDateDialog(mPositionInfo).show();
                break;
            case R.id.ib_add:
                if (mAdapter.getDataSource().size() >= 5) {
                    ToastUtil.show(this, "一次性最多添加五条就诊提醒");
                    return;
                }
                if (!CollectionUtil.isEmpty(mAdapter.getDataSource())) {
                    mDataSource.clear();
                    mDataSource.addAll(mAdapter.getDataSource());
                }

                mDataSource.add(new ReviewReminderInfo());

                mAdapter.mSelectedEditTextPosition = -1;
                mAdapter.setDataSource(mDataSource);
                break;
            case R.id.tv_choose_cycle: //提醒周期
                int position = (int) v.getTag();
                getPickerDialog(position).show();
                break;
            case R.id.tv_tips_time: //提醒时间
                getTipsTimeDialog((int) v.getTag()).show();
                break;
            case R.id.tv_del: //删除
                final int pos = (int) v.getTag();
                final AlertDialog dialog = DataCommon.getDeleteDialog(this, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mDataSource.remove(pos);
                        mAdapter.setDataSource(mDataSource);
                    }
                });
                dialog.show();
                break;
            case R.id.tv_save: //保存
                send2Net();
                break;
            case R.id.tv_switch_member:
                FamilyActivity.makeActivity(this, true, REQUEST_CODE_FAMILY);
                break;
        }
    }

    private void send2Net() {
        List<ReviewReminderInfo> dataSource = mAdapter.getDataSource();
        if (CollectionUtil.isEmpty(dataSource)) {
            ToastUtil.show(this, "请添加您的复诊提醒");
            return;
        }

        for(ReviewReminderInfo info:dataSource) {
            if(TextUtils.isEmpty(info.visitagainname)) {
                ToastUtil.show(this, "请输入复诊名称");
                return;
            }
            if(TextUtils.isEmpty(info.nextvisittime)) {
                ToastUtil.show(this, "请选择复诊时间");
                return;
            }
            if(TextUtils.isEmpty(info.visitendtime)) {
                ToastUtil.show(this, "请选择复诊结束时间");
                return;
            }
            if(TextUtils.isEmpty(info.visittype) || TextUtils.isEmpty(info.visitTypeText)) {
                ToastUtil.show(this, "请选择复诊周期");
                return;
            }
            if(TextUtils.isEmpty(info.remindtype) || TextUtils.isEmpty(info.remindtypeText)) {
                ToastUtil.show(this, "请选择提醒时间");
                return;
            }
            if(TextUtils.isEmpty(info.visitdesc)) {
                ToastUtil.show(this, "请输入复诊说明");
                return;
            }
        }

        mRemindApi.addReviewReminder(App.getInstance().getCurrentMember().id, dataSource);
    }

    private void dismissPickerDialog() {
        if (mPickerDialog != null && mPickerDialog.isShowing()) {
            mPickerDialog.dismiss();
        }
    }

    private BottomPickerDialog getPickerDialog(int tag) {
        if (mPickerDialog == null) {
            mPickerDialog = new BottomPickerDialog<>(this);
            mPickerDialog.setChooseListener((tag1, num) -> {
                dismissPickerDialog();
                int position = (int) tag1;
                List<ReviewReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);
                ReviewReminderInfo drugReminderInfo = mDataSource.get(position);
                drugReminderInfo.visitTypeText = mCycleDataSource.get(num).getName();
                drugReminderInfo.visittype = String.valueOf(num);

                Log.e("TAG", "drugReminderInfo.visittype = " + drugReminderInfo.visittype);

                mDataSource.set(position, drugReminderInfo);
                mAdapter.setDataSource(mDataSource);


            });
            mPickerDialog.setDataSource(mCycleDataSource);
        }
        mPickerDialog.setTag(tag);
        return mPickerDialog;
    }

    private DateBottomPickerDialog getDateDialog(PositionInfo tag) {
        if (mDateDialog == null) {
            mDateDialog = new DateBottomPickerDialog(this);
            mDateDialog.setDelegate((tag1, year, month, date) -> {
                dismissDateDialog();
                PositionInfo positionInfo = (PositionInfo) tag1;

                StringBuilder sb = new StringBuilder();
                sb.append(year).append("-").append(month).append("-").append(date);

                List<ReviewReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);

                ReviewReminderInfo info = mDataSource.get(positionInfo.position);
                if (positionInfo.type == HANDLE_TYPE_END_TIME) { //复诊结束时间
                    info.visitendtime = sb.toString();
                } else if (positionInfo.type == HANDLE_TYPE_START_TIME) { //下次复诊时间
                    info.nextvisittime = sb.toString();
                }
                mDataSource.set(positionInfo.position, info);
                mAdapter.setDataSource(mDataSource);
            });
        }
        mDateDialog.setTag(tag);
        return mDateDialog;
    }

    private void dismissTipsTimeDialog() {
        if (mTipsTimeDialog != null && mTipsTimeDialog.isShowing()) {
            mTipsTimeDialog.dismiss();
        }
    }

    private BottomPickerDialog getTipsTimeDialog(int tag) {
        if (mTipsTimeDialog == null) {
            mTipsTimeDialog = new BottomPickerDialog<>(this);
            mTipsTimeDialog.setChooseListener((tag1, num) -> {
                dismissTipsTimeDialog();
                int position = (int) tag1;
                List<ReviewReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);
                ReviewReminderInfo drugReminderInfo = mDataSource.get(position);
                drugReminderInfo.remindtypeText = mCycleDataSource.get(num).getName();
                drugReminderInfo.remindtype = String.valueOf(num);

                Log.e("TAG", "drugReminderInfo.remindtype = " + drugReminderInfo.visittype);

                mDataSource.set(position, drugReminderInfo);
                mAdapter.setDataSource(mDataSource);
            });
            mTipsTimeDialog.setDataSource(mTipsTimeDataSource);
        }
        mTipsTimeDialog.setTag(tag);
        return mTipsTimeDialog;
    }

    private void dismissDateDialog() {
        if (mDateDialog != null && mDateDialog.isShowing()) {
            mDateDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissDateDialog();
        dismissPickerDialog();
        dismissTipsTimeDialog();
    }

    @Override
    public void onResponse(Request request, Response response) {
        if(response.isResponseFail()) {
            ToastUtil.show(this, response.error);
        } else {
            ToastUtil.show(this, "保存成功");
            sendBroadcast(RREFRESH_DRUGREINDE);
            finish();
        }
    }
}
